package com.example.xmltohtml.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@Service
public class XmlTransformService {

    public String transformXmlToHtml(String xmlContent, String xsltPath) throws TransformerException, IOException {
        try {
            // 创建XML文档构建器
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            // 解析XML内容
            Document document = builder.parse(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
            
            // 加载XSLT模板
            ClassPathResource xsltResource = new ClassPathResource(xsltPath);
            StreamSource xsltSource = new StreamSource(xsltResource.getInputStream());
            
            // 创建转换器
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer(xsltSource);
            
            // 设置输出属性
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "html");
            
            // 执行转换
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(writer));
            
            return writer.toString();
            
        } catch (ParserConfigurationException | SAXException e) {
            log.error("Error processing XML: ", e);
            throw new TransformerException("Error processing XML", e);
        }
    }

    /**
     * 测试XML转换的main方法
     * 可以直接运行此方法来测试XML到HTML的转换
     */
    public static void main1(String[] args) {
        try {
            // 创建服务实例
            XmlTransformService service = new XmlTransformService();

            // 读取XML文件
            String xmlContent = new String(Files.readAllBytes(Paths.get("src/main/resources/xml/fund_profile_example.xml")), StandardCharsets.UTF_8);
            
            // 指定XSLT模板路径
            String xsltPath = "xslt/fund_profile.xslt";
            
            // 执行转换
            String htmlContent = service.transformXmlToHtml(xmlContent, xsltPath);
            
            // 将结果保存到文件
            String outputPath = "output/fund_profile.html";
            Files.createDirectories(Paths.get("output"));
            Files.write(Paths.get(outputPath), htmlContent.getBytes(StandardCharsets.UTF_8));
            
            System.out.println("转换成功！");
            System.out.println("HTML文件已保存到: " + new File(outputPath).getAbsolutePath());
            
        } catch (Exception e) {
            System.err.println("转换过程中发生错误：");
            e.printStackTrace();
        }
    }

    /**
     * 测试XML转换的main方法
     * 可以直接运行此方法来测试XML到HTML的转换
     */
    public static void main(String[] args) {
        try {
            // 创建服务实例
            XmlTransformService service = new XmlTransformService();

            // 读取XML文件
            String xmlContent = new String(Files.readAllBytes(Paths.get("src/main/resources/xml/CN.xml")), StandardCharsets.UTF_8);

            // 指定XSLT模板路径
            String xsltPath = "xslt/fund-report.xslt";

            // 执行转换
            String htmlContent = service.transformXmlToHtml(xmlContent, xsltPath);

            // 将结果保存到文件
            String outputPath = "output/CN.html";
            Files.createDirectories(Paths.get("output"));
            Files.write(Paths.get(outputPath), htmlContent.getBytes(StandardCharsets.UTF_8));

            System.out.println("转换成功！");
            System.out.println("HTML文件已保存到: " + new File(outputPath).getAbsolutePath());

        } catch (Exception e) {
            System.err.println("转换过程中发生错误：");
            e.printStackTrace();
        }
    }
} 